package org.lansir.af.database;

import android.content.ContentValues;
import android.database.Cursor;

/**
 * 
 * @author 蓝智宏
 *
 */
public abstract class DataRow {
	// fields
	protected Database userdb = null;
	private DataField[] vecTableDef = null;
	private ContentValues values = new ContentValues();

	// methods
	public DataRow(Database userdb) {
		this.userdb = userdb;
	}

	public Database getUserDb() {
		return userdb;
	}

	public void setTableDefinition(DataField[] vecTableDef) {
		this.vecTableDef = vecTableDef;
		// initialize field parent
		updateDataFieldsParentRow(this);
	}

	public void updateDataFieldsParentRow(DataRow row) {
		for (int i = 0; i < vecTableDef.length; i++)
			vecTableDef[i].setParentRow(row);
	}

	public void copyTableDefinition(DataRow data) {
		setTableDefinition(data.vecTableDef);
	}

	public DataField[] getTableDef() {
		return vecTableDef;
	}

	public boolean validate() {
		return false;
	}

	public ContentValues getContentValues() {
		return values;
	}

	public void setContentValues(ContentValues values) {
		this.values = values;
		updateDataFieldsParentRow(this);
	}

	public boolean copyContentValues(ContentValues values) {
		this.values = values;
		updateDataFieldsParentRow(this);
		try {
			getValuesFromDataRow();
			return true;
		} catch (Exception e) {
		}
		return false;
	}

	public DataField value(int idx) {
		return vecTableDef[idx];
	}
	
	public void clearContentValues() {
		values.clear();
	}

	public String fieldName(int idx) {
		return vecTableDef[idx].getName();
	}

	public boolean getValuesFromCursor(Cursor cr) {
		if ((cr != null) && (cr.getPosition() != -1)) {
			//一列一列的尽兴获取闹钟的数据
			for (int idx = 0; idx < vecTableDef.length; idx++) {
				DataField field = value(idx);
				// check if null value
				if (cr.isNull(idx)) {
					field.setNull();
				} else {
					final DataField.Type t = field.getType();
					// parse value by type
					if (t == DataField.Type.INT)
						field.set(cr.getLong(idx));
					if (t == DataField.Type.TEXT)
						field.set(cr.getString(idx));
					if (t == DataField.Type.BOOL)
						field.set((cr.getInt(idx) == 1) ? true : false);
					if (t == DataField.Type.FLOAT)
						field.set(cr.getFloat(idx));
				}
			}
			return true;
		}
		return false;
	}

	// sets fields values data (ContentValues values contener) from parent
	// object fields
	public abstract void setValuesForDataRow();

	// gets data from fields values (ContentValues values contener) to parent
	// object fields
	public abstract void getValuesFromDataRow();

	public abstract String getTableName();

}
